package com.yao.ecommerce.service;

import com.alibaba.fastjson.JSON;
import com.yao.ecommerce.constant.CommonConstant;
import com.yao.ecommerce.vo.JwtToken;
import com.yao.ecommerce.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * <h1>使用 RestTemplate 实现微服务通信</h1>
 * */
@Slf4j
@Service
public class UseRestTemplateService {


    private final LoadBalancerClient loadBalancerClient;

    public UseRestTemplateService(LoadBalancerClient loadBalancerClient) {
        this.loadBalancerClient = loadBalancerClient;
    }

    /**
     * <h2>从授权服务中获取 JwtToken</h2>
     * */
    public JwtToken getTokenFromAuthorityService(UsernameAndPassword usernameAndPassword) {

        //第一种方式写死url
        String url = "http://127.0.0.1:7000/ecommerce-authority-center/authority/token";
        log.info("RestTemplate request url and body: [{}], [{}]",
                url, JSON.toJSONString(usernameAndPassword));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        return new RestTemplate().postForObject(
                url,new HttpEntity<>(usernameAndPassword),JwtToken.class);
    }


    /**
     * 第二种方法，从注册中心nacos中获取URL发起请求
     * <h2>从授权服务中获取 JwtToken,且带有负载均衡</h2>
     * */
    public JwtToken getTokenFromAuthorityServiceByNacos(UsernameAndPassword usernameAndPassword) {

        ServiceInstance  serviceInstance = loadBalancerClient.choose(
                CommonConstant.AUTHORITY_CENTER_SERVICE_ID
        );
        log.info("Nacos Client Info: [{}], [{}], [{}]",
                serviceInstance.getServiceId(), serviceInstance.getInstanceId(),
                JSON.toJSONString(serviceInstance.getMetadata()));
        String url = String.format("http://%s:%s/ecommerce-authority-center/authority/token"
                ,serviceInstance.getHost(),serviceInstance.getPort());

        log.info("login request url and body: [{}], [{}]", url,
                JSON.toJSONString(usernameAndPassword));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        return new RestTemplate().postForObject(
                url,new HttpEntity<>(usernameAndPassword),JwtToken.class);
    }

}
